<template>
  <el-container class="layout-container">
    <el-aside width="220px" class="sidebar">
      <div class="logo">
        <h3>档案管理系统</h3>
      </div>
      <el-menu
        :default-active="activeMenu"
        router
        class="el-menu-vertical"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
      >
              <!-- 学生端菜单 -->
              <el-menu-item v-if="isStudent" index="/student/dashboard">
                <el-icon><HomeFilled /></el-icon>
                <span>我的首页</span>
              </el-menu-item>
              
              <el-menu-item v-if="isStudent" index="/student/apply">
                <el-icon><DocumentAdd /></el-icon>
                <el-badge :value="myPendingCount" :max="99" :hidden="myPendingCount === 0">
                  <span>我的申请</span>
                </el-badge>
              </el-menu-item>
              
              <el-menu-item v-if="isStudent" index="/student/scores">
                <el-icon><Reading /></el-icon>
                <span>我的成绩</span>
              </el-menu-item>
        
        <!-- 管理员/教师菜单 -->
        <el-menu-item v-if="!isStudent" index="/home">
          <el-icon><HomeFilled /></el-icon>
          <span>首页</span>
        </el-menu-item>
        
        <el-menu-item v-if="isAdmin || isTeacher" index="/student/manage">
          <el-icon><User /></el-icon>
          <span>学生管理</span>
        </el-menu-item>
        
        <el-menu-item v-if="isAdmin" index="/dept">
          <el-icon><OfficeBuilding /></el-icon>
          <span>院系管理</span>
        </el-menu-item>
        
        <el-menu-item v-if="isAdmin" index="/class">
          <el-icon><School /></el-icon>
          <span>班级管理</span>
        </el-menu-item>
        
        <el-menu-item v-if="isAdmin || isTeacher" index="/score">
          <el-icon><Reading /></el-icon>
          <span>成绩管理</span>
        </el-menu-item>
        
        <el-menu-item v-if="isAdmin || isTeacher" index="/record">
          <el-icon><Document /></el-icon>
          <span>档案记录</span>
        </el-menu-item>
        
        <el-menu-item v-if="isAdmin" index="/user">
          <el-icon><UserFilled /></el-icon>
          <span>用户管理</span>
        </el-menu-item>
        
        <el-divider style="margin: 10px 0; border-color: rgba(255,255,255,0.2)" />
        
        <el-menu-item v-if="isAdmin || isTeacher" index="/approval">
          <el-icon><CircleCheck /></el-icon>
          <el-badge :value="pendingApprovalCount" :max="99" :hidden="pendingApprovalCount === 0">
            <span>审批中心</span>
          </el-badge>
        </el-menu-item>
        
        <el-menu-item v-if="isAdmin || isTeacher" index="/import-export">
          <el-icon><Upload /></el-icon>
          <span>导入导出</span>
        </el-menu-item>
        
        <el-menu-item index="/message">
          <el-icon><Bell /></el-icon>
          <span>消息中心</span>
          <el-badge v-if="unreadMessageCount > 0" :value="unreadMessageCount" :max="99" class="message-badge" />
        </el-menu-item>
        
        <el-divider style="margin: 10px 0; border-color: rgba(255,255,255,0.2)" />
        
        <el-menu-item :index="isStudent ? '/student/profile' : '/profile'">
          <el-icon><Avatar /></el-icon>
          <span>个人信息</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <el-container>
      <el-header class="header">
        <div class="header-left">
          <span class="breadcrumb">{{ currentTitle }}</span>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-icon><Avatar /></el-icon>
              <span>{{ userStore.userInfo?.realName }}</span>
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-main class="main-content">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import { logout } from '@/api/auth'
import { getUnreadCount } from '@/api/message'
import { getApprovalStatistics } from '@/api/approval'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const activeMenu = computed(() => route.path)
const currentTitle = computed(() => route.meta.title as string || '')

const isAdmin = computed(() => userStore.userInfo?.roleCode === 'admin')
const isTeacher = computed(() => userStore.userInfo?.roleCode === 'teacher')
const isStudent = computed(() => userStore.userInfo?.roleCode === 'student')

// 待审批数量（管理员/教师）
const pendingApprovalCount = ref(0)
// 我的待审批申请数量（学生）
const myPendingCount = ref(0)
// 未读消息数量
const unreadMessageCount = ref(0)

// 获取统计数据
const fetchStatistics = async () => {
  try {
    // 获取未读消息数量
    const messageCount = await getUnreadCount()
    unreadMessageCount.value = messageCount || 0
    
    // 如果是管理员或教师，获取待审批数量
    if (isAdmin.value || isTeacher.value) {
      const approvalStats = await getApprovalStatistics()
      pendingApprovalCount.value = approvalStats.pendingCount || 0
    }
  } catch (error) {
    console.error('获取统计数据失败', error)
  }
}

onMounted(() => {
  fetchStatistics()
})

// 监听路由变化，刷新统计数据
watch(() => route.path, () => {
  fetchStatistics()
})

const handleCommand = async (command: string) => {
  if (command === 'logout') {
    ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await logout()
      } catch (error) {
        console.error('退出登录失败', error)
      } finally {
        userStore.logout()
        router.push('/login')
        ElMessage.success('退出成功')
      }
    })
  } else if (command === 'profile') {
    // 根据角色跳转到不同的个人信息页面
    if (isStudent.value) {
      router.push('/student/profile')
    } else {
      router.push('/profile')
    }
  }
}
</script>

<style scoped lang="scss">
.layout-container {
  width: 100%;
  height: 100%;
}

.sidebar {
  background-color: #304156;
  
  .logo {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60px;
    background-color: #2b3a4a;
    
    h3 {
      margin: 0;
      color: #fff;
      font-size: 18px;
    }
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  
  .header-left {
    .breadcrumb {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }
  }
  
  .header-right {
    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      padding: 8px 12px;
      border-radius: 4px;
      transition: background-color 0.3s;
      
      &:hover {
        background-color: #f5f5f5;
      }
    }
  }
}

.main-content {
  background-color: #f0f2f5;
  padding: 20px;
  overflow-y: auto;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

// 消息badge样式
.message-badge {
  position: absolute;
  top: 10px;
  right: 10px;
}

:deep(.el-badge__content) {
  border: 2px solid #304156;
}
</style>

